<template>
  <div class="app-container">
    <el-form :model="param" :inline="true" label-width="68px">
      <el-form-item style="width:300px">
        <div>进场日期</div>
        <el-date-picker v-model="param.inDate" type="daterange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item style="width:300px">
        <div>离场日期</div>
        <el-date-picker v-model="param.outDate" type="daterange" range-separator="~" start-placeholder="开始日期"
          end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item style="width:300px">
        <div>操作类型</div>
        <el-select v-model="param.businessType" style="width:100%" placeholder="选择操作类型">
          <el-option v-for="item in param.businessTypeOptions" :key="item.value" :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item style="width:300px">
        <div>提箱城市</div>
          <SelectCity :selectCityId="param.carryCityId" :index="1" :config="{}" @cityId="getCityId"></SelectCity>
      </el-form-item>
      <el-form-item style="width:300px">
        <div>还箱城市</div>
          <SelectCity :selectCityId="param.returnCityId" :index="1" :config="{}" @cityId="getReturnCityId"></SelectCity>
      </el-form-item>
      <el-form-item style="width:300px">
        <div>堆场</div>
        <SelectYard :selectYardName="param.yardName" :reqType="'yardName'" :config="{}" @yardId="getBoxEastYardId" style="width:100%"></SelectYard>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleReSet" :icon="Refresh" style="margin-top: 30px">重置</el-button>
        <el-button @click="getTableData" :icon="Search" type="primary" style="margin-top: 30px">查询</el-button>
      </el-form-item>
    </el-form>
    <Table v-bind="table" style="width: 100%;" @pageChange="onTablePageChange" @showDialog="showDialog" @showDialog1="showDialog1"   @activeRemark="activeRemark" @uploadAttachments="uploadAttachments" @viewAttachment="viewAttachment"></Table>
  </div>
  <!-- 修改提箱/进场日期 -->
  <el-dialog v-model="dialogData" width="500" >
    <span class="_before">
      <template v-if="dataType =='1'">修改进场日期</template>
      <template v-if="dataType =='0'">修改离场日期</template>
    </span>

    <div class="block marginTop20 text-center">
      <span class="demonstration marginRight10">
        <template v-if="dataType =='1'">进场日期</template>
        <template v-if="dataType =='0'">离场日期</template>
      </span>
      <el-date-picker v-model="newData" type="date" placeholder="请选择日期..."/>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitData">确定</el-button>
      </div>
    </template>
  </el-dialog>

   <!-- 备注 -->
   <el-dialog v-model="param.dialogVisibleRemark" :title="param.remarksTitle" width="300">
      <div style="width: 100%;text-align: center;margin-top: 20px;">
        <el-input v-model="param.remarkValSync" type="textarea" show-word-limit maxlength="200" rows="2"></el-input>
      </div>
      <div style="width: 100%;text-align: center;margin-top: 40px;">
        <el-button type="primary" @click="handleRemark" plain style="width:100px">确定</el-button>
      </div>
   </el-dialog>
   <!-- 附件操作弹窗 dialogAttachments -->
   <el-dialog v-model="dialogAttachments"  destroy-on-close width="500">
      <span class="_before marginBottom10" style="display: block;">
        <template  v-if="isViewAttachment">查看附件</template>
        <template  v-else>上传附件</template>
      </span>
      <UploadFilesImages ref="attachmentRef1" :urlList="param.urlList" :limit="10" :fileSize="10" :showNumber="'4'" :drag="true" :displayType="'2'" :type="'jpg/png/jpeg/pdf'" @updateInfo="updateInfo"></UploadFilesImages>
      <el-row justify="center" class="marginTop20">
        <!-- <el-col :span="6" class="text-center"><el-button plain @click="">重置</el-button></el-col> -->
        <el-col :span="6" class="text-center"><el-button type="primary" plain @click="submitFileList">确定</el-button></el-col>
      </el-row>
   </el-dialog>
</template>
<script lang="ts" setup>
import Table from '@/components/table'
import SelectCity from '@/components/citySelect/selectCity'
import { onMounted, reactive, watch,ref } from "vue";
import SelectYard from '@/components/citySelect/selectYard'
import { getTrackPage,updateTrackInOrOutDate,updateTrackRemark,updateContainerTrackFile } from '@/api/boxManage/index'
import UploadFilesImages from '@/components/upload/uploadFiles-Images'
import {Refresh,Search} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus/es';



const props = defineProps({
  containerNo: {
    type: Number,
    default: 0
  }
})
// 5 - 提箱  10 - 还箱  15-卖箱  20-退款  25-买箱
const param = reactive({
  pageNum:'1',
  pageSize:'10',
  businessType: '',
  carryCityId:'',
  returnCityId:'',
  boxEastYardId:'',
  yardName:'',
  inDate:[],
  outDate:[],
  businessTypeOptions: [
    { value: 5, label: '提箱', },
    { value: 10, label: '还箱', },
    { value: 15, label: '卖箱', },
    { value: 20, label: '退款', },
    { value: 25, label: '买箱', },
  ],
  dialogVisibleRemark:false,
  remarksTitle:'',
  remarkValSync:'',
  urlList:[]
})
const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'containerNo', colWidth: '130', title: '箱号', isCheck: true },
    { key: 'boxType', colWidth: '80', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
    { key: 'boxCondition', colWidth: '80', title: '箱况', type: 'filter', filter: { 5: '全新', 10: '次新', 15: '适货' }, isCheck: true },
    { key: 'businessType', colWidth: '80', title: '操作类型', type: 'filter', filter: { 5: '提箱', 10: '还箱',15:'卖箱',20:'退款',25:'买箱' }, isCheck: true },
    { key: 'carryCityName', colWidth: '80', title: '提箱城市', type: 'text', isCheck: true },
    { key: 'returnCityName', colWidth: '80', title: '还箱城市', type: 'text', isCheck: true },
    { key: 'inDate', key1:'businessType', key2:'refCategory', colWidth: '120', title: '进场日期', type: 'dialog',icon:'EditPen',showVal:'5',command:'showDialog', containerClassify:'containerClassify',isCheck: true },
    { key: 'inDays', colWidth: '80', title: '堆存天数', type: 'day', isCheck: true },
    { key: 'outDate',key1:'businessType', key2:'refCategory',colWidth: '120', title: '离场日期', type: 'dialog',icon:'EditPen',showVal:'5',command:'showDialog1', isCheck: true },
    { key: 'outDays', colWidth: '80', title: '离场天数', type: 'day', isCheck: true },
    { key: 'overDays', colWidth: '80', title: '超期天数', type: 'day', isCheck: true },
    { key: 'refNo', colWidth: '100', title: '单据号', type: '<a>', isCheck: true },
    { key: 'agentName', colWidth: '100', title: '客户', type: 'text', isCheck: true },
    { key: 'yardName', colWidth: '100', title: '堆场', type: 'text', isCheck: true },
    { key: 'oidContainerNo', colWidth: '100', title: '原箱号', type: 'text', isCheck: true },
    // { key: 'remark', colWidth: '120', title: '备注', type: 'remark', isCheck: true },
    {
      key: 'remark', key2:'refCategory', colWidth: '120', title: '备注', type: 'remark', isCheck: true,fixed: 'right',
      buttons: [
        {
          icon: 'Plus',
          command: 'activeRemark',
          // name: '添加备注',
          isShow: (row: any) => {
            return !row.remark && row.returnBoxStatus != 20;
            //returnBoxStatus 还箱单状态: 5-已发放 10-已下载 15-还箱中 20-已完成 25-已过期
          },
        },
        {
          icon: 'Edit',
          command: 'activeRemark',
          // name: '修改备注',
          showOnlyKey: true,
          // isReadOnly: (row: any) => {
          //   return row.returnBoxStatus != 20;
          // },
          isShow: (row: any) => {
            return row.remark;
          },
        },
      ],
    },
    {
      key: 'fileList', key2:'refCategory', colWidth: '120', title: '附件', type: 'operate', isCheck: true,fixed: 'right',
      buttons: [
        {
          icon: 'Upload',
          command: 'uploadAttachments',
          content: '上传附件',
          isShow: (row: any) => {
            return !row.fileList;
          },
        },
        {
          icon: 'View',
          command: 'viewAttachment',
          content: '查看附件',
          isShow: (row: any) => {
            return row.fileList;
          },
        },
      ],
    },

  ],
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  },
});

onMounted(() => {
  getTableData();
});
watch(() => props.containerNo, () => {
  getTableData()
})

function getTableData() {
  let data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    containerNo: props.containerNo,
    businessType: param.businessType,
    boxEastYardId: param.boxEastYardId,
    carryCityId: param.carryCityId,// 提箱城市
    returnCityId: param.returnCityId,// 还箱城市
  };

  if (param.inDate && param.inDate.length > 1) {
    data.beginInDate = param.inDate[0]
    data.endInDate = param.inDate[1]
  }
  if (param.outDate && param.outDate.length > 1) {
    data.beginOutDate = param.outDate[0]
    data.endOutDate = param.outDate[1]
  }
  getTrackPage(data).then(res => {
    table.data = res.data.list;
    table.config.total = res.data.total;
    table.data.forEach((item: any) => {
      let days = item.outDays - item.boxUsagePeriod
      item.overDays = days > 0 ? days : 0
    })
  });
  table.config.loading = false;
}
const handleReSet = () => {
  param.inDate = []
  param.outDate = []
  param.businessType = ''
  param.carryCityId = ''
  param.returnCityId = ''
  param.boxEastYardId = ''
  param.yardName = ''
  getTableData()
}

const getCityId = (id: string) => {
  param.carryCityId = id
}
const getReturnCityId = (id: string) => {
  param.returnCityId = id
}

const getBoxEastYardId = (info: string) => {
  param.boxEastYardId = info[0]?.id
}

// 修改日期
const dialogData = ref(false)
const dataType = ref("1")  //1:进场日期  0:离场日期
const newData = ref() 
const itemId = ref(Number)
const showDialog = (row: any) => {
      newData.value = row.inDate
      itemId.value = row.id
      dataType.value = "1"
      dialogData.value = true
}
const showDialog1 = (row: any)  =>{ 
  newData.value = row.outDate
  itemId.value = row.id
  dataType.value = "0"
  dialogData.value = true
} 
// 提交修改日期
const submitData = () =>{
 let reqParam = {
    inDate:dataType.value == "1"? newData.value : null,
    outDate: dataType.value == "0"? newData.value : null

 }
 updateTrackInOrOutDate(itemId.value,reqParam).then(res=>{ 
    if(res.code == '00000'){
      getTableData()
      dialogData.value = false
      ElMessage.success("修改成功！")
    }else{
      ElMessage.warning("修改失败！")
    }
 })
}

const remarkId = ref(null)
// 编辑备注
const activeRemark = (row: any) => {
  remarkId.value = row.id
  param.remarkValSync = row.remark;
  param.dialogVisibleRemark = true;
  if (row.remark) {
    param.remarksTitle = '编辑备注'
  } else {
    param.remarksTitle = '添加备注'
  }
};

const isViewAttachment = ref(true); // 是否查看附件
// 上传附件
const updateImg = ref([])
const updateInfo = (row) =>{
  updateImg.value = row
}
const dialogAttachments = ref(false);
const eiitAttachmentsId = ref(Number);
const uploadAttachments = (row: any) => { 
  isViewAttachment.value = false;
  dialogAttachments.value = true;
  eiitAttachmentsId.value = row.id;
};

const submitFileList = async () => { 
  if(!updateImg.value.length) return ElMessage.error('请先选择需要上传的文件') 
  updateContainerTrackFile(eiitAttachmentsId.value,{fileList:JSON.stringify(updateImg.value)}).then((res: any) => { 
      if (res.code === '00000') {
        getTableData()
        dialogAttachments.value = false;
        ElMessage.success('附件上传成功');
      }else {
        ElMessage.error('附件上传失败');
      }
    });
};
// 查看附件
const viewAttachment = (row: any) => {
  isViewAttachment.value = true;
  eiitAttachmentsId.value = row.id;
  dialogAttachments.value = true;
  param.urlList = row.fileList;
};


//添加|修改备注
const handleRemark = () => {
  const data = {remark: param.remarkValSync }
  updateTrackRemark(remarkId.value,data).then((res: any) => {
    ElMessage.success('备注修改成功');
    param.dialogVisibleRemark = false;
    getTableData()
  })
};
//分页
function onTablePageChange(page: any) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

</script>
<style scoped></style>
